Sqlalchemy automap Demo

1
2
3
from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.orm import Session
from sqlalchemy.ext.automap import automap_base
1
2
3
4
5
6
if __name__ == '__main__':
engine_str = "mysql+pymysql://user:password@host:port/employees?charset=utf8mb4"
engine = create_engine(engine_str, echo=True)
session = Session(engine)
Base = automap_base()
Base.prepare(engine, reflect=True)
1
2
3
4
# 查询测试
result = session.query(Base.classes.user).all()
for i in result:
print(i.id)
1
2
3
4
5
6
7
8
9
10
11
12
# orm 映射
User = Base.classes.user
Customers = Base.classes.Customers
Orders = Base.classes.Orders

result = session.query(Customers, Orders).filter_by(cust_id=1000000001).first()
# print(result)
for i in result:
if isinstance(i, Customers):
print(i.cust_name)
if isinstance(i, Orders):
print(i.order_date)